<template>
  <div class="system-building-management">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-bar">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
          <el-form-item label="办事事务名称" prop="bsswmc">
            <el-input
              v-model="queryParams.bsswmc"
              placeholder="请输入办事事务名称"
              clearable
              style="width: 220px;"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="事务申请人" prop="swblr">
            <el-input
              v-model="queryParams.swblr"
              placeholder="请输入事务申请人"
              clearable
              style="width: 220px;"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="采集时间" prop="sjcjsj">
            <el-date-picker
              v-model="sjcjsjDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYYMMDD HHmmss"
              @change="handleSjcjsjRangeChange"
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item label="上报状态" prop="reportStatus">
            <el-select v-model="queryParams.reportStatus" placeholder="请选择上报状态" clearable style="width: 180px;">
              <el-option label="未上报" value="0" />
              <el-option label="已上报" value="1" />
              <el-option label="上报失败" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="handleQuery" style="margin-left: 8px;">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetQuery" style="margin-left: 8px;">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </div>
        <div class="header-title"><h3>在线事务办理数据数据管理</h3></div>
        <div class="placeholder">
          <el-tooltip content="刷新" placement="top">
            <el-button circle @click="getList">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>

      <div class="table-body">
        <el-table
          v-loading="loading"
          :data="dataList"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%"
          highlight-current-row
          @row-click="handleRowClick"
          @row-dblclick="handleRowDblClick"
          :height="'calc(75vh - 160px)'"
          stripe
          size="default"
          :row-style="{ height: '42px' }"
          :cell-style="{ padding: '2px' }"
        >
          <el-table-column type="selection" width="45" fixed="left" />
          <el-table-column type="index" label="序号" width="50" fixed="left" />
          <el-table-column prop="id" label="ID" min-width="90" align="center" sortable="custom" />
          <el-table-column prop="zjsjwyxbs" label="唯一性标识" min-width="160" show-overflow-tooltip sortable="custom" />
          <el-table-column prop="xxdm" label="学校代码" min-width="120" show-overflow-tooltip sortable="custom" />
          <el-table-column prop="bsswmc" label="办事事务名称" min-width="180" show-overflow-tooltip sortable="custom" />
          <el-table-column prop="bsswlxm" label="办事事务类型" min-width="150" show-overflow-tooltip sortable="custom" />
          <el-table-column prop="rylxm" label="人员类型" min-width="150" show-overflow-tooltip sortable="custom" />
          <el-table-column prop="sqsj" label="申请时间" min-width="160" align="center" sortable="custom" />
          <el-table-column prop="swblr" label="事务申请人" min-width="120" align="center" sortable="custom" />
          <el-table-column prop="blsj" label="办理时间" min-width="160" align="center" sortable="custom" />
          <el-table-column prop="sjcjsj" label="数据采集时间" min-width="160" align="center" sortable="custom" />
          <el-table-column prop="createTime" label="创建时间" min-width="160" align="center" sortable="custom" />
          <el-table-column label="上报状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getReportStatusTagType(row.reportStatus) as any" size="small">{{ getReportStatusText(row.reportStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="启用状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.enableStatus === '1' ? 'success' : 'danger'" size="small">{{ row.enableStatus === "1" ? "启用" : "禁用" }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" min-width="160" align="center" sortable="custom" />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button link type="primary" size="small" @click="handleView(row)"><el-icon><View /></el-icon>查看</el-button>
                <el-button link type="primary" size="small" @click="handleEdit(row)"><el-icon><Edit /></el-icon>编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDelete(row)"><el-icon><Delete /></el-icon>删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <span class="total-info">共 {{ total }} 条</span>
        <div class="pagination-controls">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 200, 500]"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑/查看对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
      class="custom-dialog"
      destroy-on-close
      @close="handleFormClose"
    >
      <el-form v-if="dialogMode !== 'view'" ref="formRef" :model="form" :rules="formRules" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="唯一性标识" prop="zjsjwyxbs">
              <el-input v-model="form.zjsjwyxbs" placeholder="可不填，后端自动生成32位唯一编码" maxlength="32" show-word-limit style="text-transform: uppercase" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="学校代码" prop="xxdm">
              <el-input v-model="form.xxdm" placeholder="系统自动获取学校代码" maxlength="10" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 18px;">
            <el-form-item label="办事事务名称" prop="bsswmc">
              <el-input v-model="form.bsswmc" placeholder="请输入办事事务名称" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="办事事务类型码" prop="bsswlxm">
              <el-select v-model="form.bsswlxm" placeholder="请选择办事事务类型" style="width: 100%" clearable>
                <el-option v-for="item in dictData.bsswlxmOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="人员类型码" prop="rylxm">
              <el-select v-model="form.rylxm" placeholder="请选择人员类型" style="width: 100%" clearable>
                <el-option v-for="item in dictData.rylxmOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="申请时间" prop="sqsj">
              <el-date-picker v-model="form.sqsj" type="datetime" placeholder="请选择申请时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYYMMDD HHmmss" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="事务申请人" prop="swblr">
              <el-input v-model="form.swblr" placeholder="请输入事务申请人姓名" maxlength="36" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="办理时间" prop="blsj">
              <el-date-picker v-model="form.blsj" type="datetime" placeholder="请选择办理时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYYMMDD HHmmss" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="数据采集时间" prop="sjcjsj">
              <el-date-picker v-model="form.sjcjsj" type="datetime" placeholder="请选择数据采集时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYYMMDD HHmmss" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-bottom: 18px;">
            <el-form-item label="启用状态" prop="enableStatus">
              <el-select v-model="form.enableStatus" placeholder="请选择启用状态" style="width: 100%">
                <el-option label="禁用" value="0" />
                <el-option label="启用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 查看模式 -->
      <div v-else class="detail-view">
        <el-descriptions class="detail-descriptions" :column="2" size="large" border>
          <el-descriptions-item label="唯一性标识"><div class="detail-value">{{ form.zjsjwyxbs || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="学校代码"><div class="detail-value">{{ form.xxdm || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="办事事务名称"><div class="detail-value">{{ form.bsswmc || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="办事事务类型"><div class="detail-value">{{ (form as any).bsswlxmText || form.bsswlxm || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="人员类型"><div class="detail-value">{{ (form as any).rylxmText || form.rylxm || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="申请时间"><div class="detail-value">{{ form.sqsj || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="事务申请人"><div class="detail-value">{{ form.swblr || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="办理时间"><div class="detail-value">{{ form.blsj || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="数据采集时间"><div class="detail-value">{{ form.sjcjsj || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="启用状态">
            <el-tag :type="form.enableStatus === '1' ? 'success' : 'danger'" size="small">{{ form.enableStatus === "1" ? "启用" : "禁用" }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="上报状态">
            <el-tag :type="getReportStatusTagType((form as any).reportStatus as string) as any" size="small">{{ getReportStatusText((form as any).reportStatus as string) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间"><div class="detail-value">{{ (form as any).createTime || "-" }}</div></el-descriptions-item>
          <el-descriptions-item label="更新时间"><div class="detail-value">{{ (form as any).updateTime || "-" }}</div></el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" :loading="submitLoading" @click="handleFormSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import { Search, Refresh, Plus, Edit, Delete, View, Download } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import  '@/styles/index.scss'
// API导入
import {
  getOdsZxswblsjPage,
  getOdsZxswblsjById,
  addOdsZxswblsj,
  updateOdsZxswblsj,
  deleteOdsZxswblsj,
  batchDeleteOdsZxswblsj,
  exportOdsZxswblsj,
  getDictOptions,
  getSystemSchoolCode,
  type OdsZxswblsjInfo,
  type OdsZxswblsjQuery,
  type OdsZxswblsjForm,
} from "@/api-data/data/data_base/zygfw/ods_zxswblsj";

// 响应式数据
const loading = ref(false);
const dataList = ref<OdsZxswblsjInfo[]>([]);
const total = ref(0);
const dialogVisible = ref(false);
const dialogMode = ref<"add" | "edit" | "view">("add");
const selectedIds = ref<number[]>([]);
const submitLoading = ref(false);

// 计算属性
const dialogTitle = computed(() => {
  switch (dialogMode.value) {
    case "add": return "新增在线事务办理数据";
    case "edit": return "编辑在线事务办理数据";
    case "view": return "查看在线事务办理数据";
    default: return "在线事务办理数据";
  }
});

// 搜索条件
const queryParams = reactive<OdsZxswblsjQuery>({
  bsswmc: "",
  swblr: "",
  sjcjsjStart: "",
  sjcjsjEnd: "",
  reportStatus: "",
  pageNum: 1,
  pageSize: 20,
});

// 表单相关
const form = reactive<OdsZxswblsjForm>({
  id: undefined,
  zjsjwyxbs: "",
  xxdm: "",
  bsswmc: "",
  bsswlxm: "",
  rylxm: "",
  sqsj: "",
  swblr: "",
  blsj: "",
  sjcjsj: "",
  enableStatus: "1",
});

const formRef = ref<FormInstance>();
const queryFormRef = ref<FormInstance>();
const systemSchoolCode = ref("");

// 表单验证规则
const formRules = reactive({
  zjsjwyxbs: [{ validator: (_rule: any, value: string, callback: Function) => {
      if (!value) { callback(); } 
      else if (value.length !== 32) { callback(new Error('唯一编码必须是32位')); } 
      else if (!/^[A-Z0-9]+$/.test(value)) { callback(new Error('只能包含大写字母和数字'));} 
      else { callback(); }
    }, trigger: 'blur'
  }],
  xxdm: [{ required: true, message: "学校代码不能为空", trigger: "blur" }],
  bsswmc: [{ required: true, message: "请输入办事事务名称", trigger: "blur" }, { max: 200, message: "长度不能超过200位", trigger: "blur" }],
  bsswlxm: [{ required: true, message: "请选择办事事务类型码", trigger: "change" }],
  rylxm: [{ required: true, message: "请选择人员类型码", trigger: "change" }],
  sqsj: [{ required: true, message: "请选择申请时间", trigger: "change" }],
  swblr: [{ max: 36, message: "事务申请人长度不能超过36位", trigger: "blur" }],
  sjcjsj: [{ required: true, message: "请选择数据采集时间", trigger: "change" }],
});

// 字典数据
const dictData = reactive<{ bsswlxmOptions: Array<{label: string; value: string}>; rylxmOptions: Array<{label: string; value: string}> }>({
  bsswlxmOptions: [],
  rylxmOptions: [],
});

// 获取字典数据
const loadDictData = async () => {
  try {
    const [bsswlxmRes, rylxmRes]: any = await Promise.all([
      getDictOptions('BSSWLXDM'),
      getDictOptions('RYLXDM'),
    ]);
    if (bsswlxmRes.data.code === 200) dictData.bsswlxmOptions = (bsswlxmRes.data.data || []) as any[];
    if (rylxmRes.data.code === 200) dictData.rylxmOptions = (rylxmRes.data.data || []) as any[];
  } catch (error) {
    console.error("获取字典数据失败:", error);
    ElMessage.error("获取字典数据失败");
  }
};

// 获取上报状态
const getReportStatusText = (status: string) => (({ "0": "未上报", "1": "已上报", "2": "上报失败" })[status] || "未知");
const getReportStatusTagType = (status: string) => (({ "0": "info", "1": "success", "2": "danger" })[status] || "warning");

// 搜索-采集时间范围
const sjcjsjDateRange = ref<[string, string] | undefined>(undefined);
const handleSjcjsjRangeChange = (dates: [string, string] | null) => {
  if (dates && dates.length === 2) {
    queryParams.sjcjsjStart = dates[0];
    queryParams.sjcjsjEnd = dates[1];
  } else {
    queryParams.sjcjsjStart = "";
    queryParams.sjcjsjEnd = "";
  }
};

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const response :any = await getOdsZxswblsjPage(queryParams);
    if (response.data.code === 200) {
      dataList.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg || "查询失败");
    }
  } catch (error) {
    console.error("查询数据失败:", error);
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => { queryParams.pageNum = 1; getList(); };
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  sjcjsjDateRange.value = undefined;
  queryParams.sjcjsjStart = "";
  queryParams.sjcjsjEnd = "";
  queryParams.pageNum = 1;
  getList();
};

const resetForm = () => {
  Object.assign(form, {
    id: undefined, zjsjwyxbs: "", xxdm: systemSchoolCode.value, bsswmc: "", bsswlxm: "",
    rylxm: "", sqsj: "", swblr: "", blsj: "", sjcjsj: "", enableStatus: "1", reportStatus: undefined,
  });
  formRef.value?.clearValidate();
};

const handleAdd = () => { resetForm(); dialogMode.value = "add"; dialogVisible.value = true; };

const handleEdit = async (row: OdsZxswblsjInfo) => {
  try {
    const response :any = await getOdsZxswblsjById(row.id);
    if (response.data.code === 200) {
      Object.assign(form, response.data.data);
      dialogMode.value = "edit";
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || "获取详情失败");
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

const handleView = async (row: OdsZxswblsjInfo) => {
  try {
    const response :any = await getOdsZxswblsjById(row.id);
    if (response.data.code === 200) {
      Object.assign(form, response.data.data);
      dialogMode.value = "view";
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || "获取详情失败");
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    ElMessage.error("获取详情失败");
  }
};

const handleDelete = async (row: OdsZxswblsjInfo) => {
  try {
    await ElMessageBox.confirm("确定要删除这条数据吗？", "提示", { type: "warning" });
    const response :any = await deleteOdsZxswblsj(row.id);
    if (response.data.code === 200) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(response.data.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") ElMessage.error("删除失败");
  }
};

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return ElMessage.warning("请选择要删除的数据");
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条数据吗？`, "提示", { type: "warning" });
    const response:any = await batchDeleteOdsZxswblsj(selectedIds.value);
    if (response.data.code === 200) {
      ElMessage.success("批量删除成功");
      selectedIds.value = [];
      getList();
    } else {
      ElMessage.error(response.data.msg || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") ElMessage.error("批量删除失败");
  }
};

const handleExport = async () => {
  try {
    const response = await exportOdsZxswblsj(queryParams);
    const blob = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = `在线事务办理数据_${new Date().getTime()}.xlsx`;
    link.click();
    window.URL.revokeObjectURL(link.href);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败");
  }
};

const handleFormSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    const response :any = dialogMode.value === "add" ? await addOdsZxswblsj(form) : await updateOdsZxswblsj(form);
    if (response.data.code === 200) {
      ElMessage.success(dialogMode.value === "add" ? "新增成功" : "修改成功");
      dialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(response.data.msg || "操作失败");
    }
  } catch (error) {
    console.error("提交表单失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

const handleFormClose = () => { dialogVisible.value = false; resetForm(); };
const handleRowClick = () => {};
const handleSelectionChange = (selection: OdsZxswblsjInfo[]) => { selectedIds.value = selection.map((item) => item.id); };
const handleRowDblClick = (row: OdsZxswblsjInfo) => { handleView(row); };
const handleSizeChange = (size: number) => { queryParams.pageSize = size; queryParams.pageNum = 1; getList(); };
const handleCurrentChange = (page: number) => { queryParams.pageNum = page; getList(); };

const getSystemSchoolCodeData = async () => {
  try {
    const response:any = await getSystemSchoolCode();
    if (response.data.code === 200) {
      systemSchoolCode.value = response.data.data;
      form.xxdm = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取学校代码失败");
    }
  } catch (error) {
    console.error("获取系统学校代码失败:", error);
    ElMessage.error("获取学校代码失败");
  }
};

onMounted(() => {
  getSystemSchoolCodeData();
  loadDictData();
  getList();
});
</script>

 